let myUrl = require("../utils/url.js")

let requests = require("../utils/requests.js")

/**
 * 获取试卷列表
 */
export function getPaper(paper_type){
  return requests.fatch({
    load: 1,
    url: myUrl.mainUrl + "paper/?paper_type=" + paper_type,
  })
}

/**
 * 试卷详情
 */
export function getPaperDetial(paperId){
  return requests.fatch({
    load: 1,
    url: myUrl.mainUrl + "paper/" + paperId + "/",
    header: { "Authorization": "JWT " + wx.getStorageSync('token') },
  })
}

/**
 * 获取试卷轮播图
 */
export function getPaperLoopImage(){
  return requests.fatch({
    load: 0,
    url: myUrl.mainUrl + "paperloop/",
  })
}

/**
 * 获取一级试卷分类
 */
export function getLevel1PaperCategory(){
  return requests.fatch({
    load: 0,
    url: myUrl.mainUrl + "papertype/?category_type=1"
  })
}

/**
 * 获取二级试卷分类
 */
export function getLevel2PaperCategory(parentCategory){
  return requests.fatch({
    load: 0,
    url: myUrl.mainUrl + "papertype/?parent_category="+parentCategory
  })
}

export function singlePay(singer_mobile, paper_id){
  return requests.fatch({
    url: myUrl.mainUrl + "paperorder/",
    load: 1,
    data: {
      singer_mobile: singer_mobile,
      paper_id: paper_id
    },
    header: { "Authorization": "JWT " + wx.getStorageSync('token') },
    method: "POST"
  })
}

export function getUserPaper(){
  return requests.fatch({
    load: 1,
    url: myUrl.mainUrl + "userpaper/",
    header: { "Authorization": "JWT " + wx.getStorageSync('token') },
  })
}

/**
* 判断是否购买试卷
*/
export function userHasPaper(paper_id){
  return requests.fatch({
    url: myUrl.mainUrl + "havepaper/" + paper_id + "/",
    header: { "Authorization": "JWT " + wx.getStorageSync('token') },
  })
}

/**
 * 试卷收藏
 */
export function paperFav(paper_id){
  return requests.fatch({
    url: myUrl.mainUrl + "favpaper/",
    data: {
      "test_paper": paper_id
    },
    method: 'POST',
    header: { "Authorization": "JWT " + wx.getStorageSync('token') },
  })
}


/**
 * 移除收藏
 */
export function removePaperFav(paper_id){
  return requests.fatch({
    url: myUrl.mainUrl + "favpaper/" + paper_id,
    method: 'DELETE',
    header: { "Authorization": "JWT " + wx.getStorageSync('token') }
  })
}


/**
 * 收藏
 */
export function paperFavChoice(paper){
  let _userFavPaper = wx.getStorageSync("userFavPaper")
  let isFav = false;
  let index = -1;
  for(let i = 0; i < _userFavPaper.length; i ++){
    if(paper.id == _userFavPaper[i].id){
      isFav = true
      index = i
      break;
    }
  }

  if(isFav){
    _userFavPaper.splice(index, 1)
    wx.setStorageSync("userFavPaper", _userFavPaper)
    // 移除
    removePaperFav(paper.id)
  }else{
    _userFavPaper.push(paper)
    wx.setStorageSync("userFavPaper", _userFavPaper)
    // 添加
    paperFav(paper.id)
  }


}